package czx.wt.util.validcode;

import czx.wt.util.response.CommResponseEnum;
import czx.wt.util.response.Resp;
import czx.wt.util.response.ResponseData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ChenZhiXiang
 * @version 1.0.0
 * @Description TODO
 * @createTime 2018年12月25日 21:17:00
 */
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        if (StringUtils.equals("/login/login",httpServletRequest.getRequestURI()) &&
                StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(),"post")){
            ImageCode imageCode = (ImageCode) httpServletRequest.getSession().getAttribute(ValidController.SESSION_KEY);
            if (imageCode.getCode() != null && StringUtils.equalsIgnoreCase(imageCode.getCode(),httpServletRequest.getParameter("imageCode"))){
                //验证码过期
                if (imageCode.isExpire()){
                    try {
                        httpServletRequest.removeAttribute(ValidController.SESSION_KEY);
                        Resp.outResp(httpServletResponse,ResponseData.failureResponse(CommResponseEnum.validCode2));
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                httpServletRequest.removeAttribute(ValidController.SESSION_KEY);
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            } else {
                try {
                    httpServletRequest.removeAttribute(ValidController.SESSION_KEY);
                    Resp.outResp(httpServletResponse,ResponseData.failureResponse(CommResponseEnum.validCode1));
                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
        return;
    }
}
